<?php
class member{
	private $app;
	private $data = null;
	public $message = null;
	
	public function __construct(){
		global $app;
		$app->{"cache"} =& $this;
		$this->app =& $app;
		if(! empty($this->app->session->read("member"))){
			$result = $app->db->select("members", "*", "WHERE `login`='".$this->app->session->read("member")."'");
			$this->data = $result[0];
		}
	}
	
	/**
	 * 判斷使用者是否登入
	 * @return boolean
	 */
	public function is_ligin(){
		return ! empty($data);
	}
	
	/**
	 * 新增用戶
	 * @param string $login
	 * @param string $password
	 * @param string $email
	 * @param string $display
	 * @return boolean
	 */
	public function register($login, $password, $email, $display = null){
		if(! empty($this->data) && permission){
			$this->message = _("請不要重複註冊。");
			return false;
		}
			
		$display = empty($display)? $login: $display;
		switch(true){
			case ! preg_match("/^[-_a-z0-9]{3,50}/i", $login):
				$this->message = _("帳號不合法，只能使用「-」、「_」、英文、數字，且長度需在 3~50 之內。");
				return false;
				break;
			case ! preg_match("/^[-_a-z0-9]{6,64}/i", $password):
				$this->message = _("密碼不合法，只能使用「-」、「_」、英文、數字，且長度需在 6~64 之內。");
				return false;
				break;
			case ! preg_match("/[a-z0-9\._\+]+@([a-z0-9\.-]\.)*[a-z]+/i", $email):
				$this->message = _("Email不合法，請輸入真實Email。");
				return false;
				break;
		}
		$this->app->db->insert("members", array("login", "password", "email", "display"), array($login, $password, $email, $display, date("Y-m-d H:i:s")));
	}
	
	/**
	 * 用戶登入
	 * @param string $login - 可輸入密碼、Email
	 * @param string $password
	 * @return boolean
	 */
	public function login($login, $password){
		$col = preg_match("/[a-z0-9\._\+]+@([a-z0-9\.-]\.)*[a-z]+/i", $login)? "email": "login";
		if(! $result = $app->db->select("members", "*", "WHERE `login`='".$this->app->session->read("member")."'")){
			$this->message = _("帳號 or Email輸入錯誤。");
		 	return false;
		}
		$realpass = $result[0]["password"];
		$hasher = new PasswordHash(8, FALSE);
		if($hasher->CheckPassword($password, $realpass)){
			$this->app->session->write("member", $result[0]["login"]);
			return true;
		}else{
			$this->message = _("密碼錯誤。");
			return false;
		}
	}
	
	/**
	 * 登出
	 */
	public function logout(){
		if(! empty($this->data)){
			$this->app->session->destroy();
		}
	}
}
?>